class HotPostsController < ApplicationController
  before_filter :authorize_for_admin,:except => :seo
  before_filter :authorize, :except => :seo
  layout 'base.html', :except => [:seo,:pre_lz_post,:next_lz_post]
  
  def index
    params[:search_type] = 'all' if params[:search_type].blank?
    params[:hot_post_type_id] = '%' if params[:hot_post_type_id].blank?
    params[:page] = 1 if params[:page].blank?
    params[:order] = 'updated_at' if params[:order].blank?
    params[:by] = 'desc' if params[:by].blank?
    def params.order_by
      "hot_posts.#{self[:order]} #{self[:by]}"
    end
    @hot_posts = HotPost.paginate :conditions => [
        'status like ? and hot_post_type_id like ?',
        params[:search_type] == 'all' ? '%' : params[:search_type],
        params[:hot_post_type_id]
      ],
      :page => params[:page],
      :per_page => 10,
      :order => params.order_by
    @hot_post_types = HotPostType.all
    def @hot_post_types.hot_posts_count
      each_with_object({ :count => 0}) do |type, hash|
        hash[:count] += type.hot_posts_count
      end[:count]
    end
    @hot_post_type_name = params[:hot_post_type_id] == '%' ? '全部' : HotPostType.find(params[:hot_post_type_id]).name
    respond_to do |format|
      format.html do
        @seo_title = "麦吐司网-追热贴管理"
        @seo_keywords = @seo_title
        @seo_description = @seo_title
      end
      format.js do
        render :layout => false
      end
    end
  end

  def reactive
    @hot_post = HotPost.find(params[:id])
    @hot_post.actived!
    render :text => 'success', :status => 200
  end

  def to_be_end
    @hot_post = HotPost.find(params[:id])
    @hot_post.end!
    render :text => 'success', :status => 200
  end

  def seo
    @hot_posts = HotPost.all(:conditions =>['status != ?', 'hidden'])
  end
  
  def pre_lz_post
    @sub_hot_post = SubHotPost.find(params[:id])
    params[:author] = @sub_hot_post.hot_post.author
    params[:hot_post_id] = @sub_hot_post.hot_post_id
    @post = SubHotPost.last(
      :conditions => [
        ' id < :id and hot_post_id = :hot_post_id and author = :author',
        params
      ],
      :order => 'id asc'
    )
    @position = SubHotPost.count(
      :conditions => [
        ' id < :id and hot_post_id = :hot_post_id and author = :author',
        params
      ],
      :order => 'id asc'
    )
  end
  
  def next_lz_post
    @sub_hot_post = SubHotPost.find(params[:id])
    params[:author] = @sub_hot_post.hot_post.author
    params[:hot_post_id] = @sub_hot_post.hot_post_id
    @post = SubHotPost.first(
      :conditions => [
        ' id > :id and hot_post_id = :hot_post_id and author = :author',
        params
      ],
      :order => 'id asc'
    )
    @position = SubHotPost.count(
      :conditions => [
        ' id <= :id and hot_post_id = :hot_post_id and author = :author',
        params
      ],
      :order => 'id asc'
    ) + 1
  end

end
